package com.example.satokentest.service.impl;

import com.example.satokentest.common.response.Result;
import com.example.satokentest.dao.UserMapper;
import com.example.satokentest.model.dto.LoginDTO;
import com.example.satokentest.model.entity.User;
import com.example.satokentest.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.dev33.satoken.stp.StpUtil;
import com.example.satokentest.common.util.PasswordUtil;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<?> login(LoginDTO loginDTO) {
        User user = userMapper.findByUsername(loginDTO.getUsername());
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 使用PasswordUtil进行密码验证
        if (!PasswordUtil.matches(loginDTO.getPassword(), user.getPassword())) {
            return Result.error("密码错误");
        }

        // 登录成功，使用Sa-Token记录登录状态
        StpUtil.login(user.getId());
        
        return Result.success(StpUtil.getTokenValue());
    }

    @Override
    public Result<?> logout() {
        StpUtil.logout();
        return Result.success(null);
    }

    @Override
    public Result<?> getUserInfo() {
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        user.setPassword(null); // 清除密码
        return Result.success(user);
    }
} 